// 持久化 localStorage
import { computed } from 'vue'

//获取到的值进行转换
const parseJSON = (value: string) => {
  try {
    return value === 'undefined' ? undefined : JSON.parse(value ?? '')
  } catch (error) {
    return undefined
  }
}

// 获取值(computed)，设置值，删除值
export function useLocalStorage<T>(key: string, initalValue: T) {
  //读取数据
  const readValue = () => {
    try {
      const item = localStorage.getItem(key)
      return item ? parseJSON(item) : initalValue
    } catch (error) {
      return initalValue
    }
  }
  //获取数据
  const storedValue = computed(() => readValue())
  //设置数据
  const setValue = (value: T) => {
    try {
      //如果传入的是一个方法
      const newValue = value instanceof Function ? value(storedValue) : value
      localStorage.setItem(key, JSON.stringify(newValue))
    } catch (error) {
      //无
    }
  }
  const removeValue = () => {
    localStorage.removeItem(key)
  }
  return {
    value: storedValue,
    setValue,
    removeValue
  }
}
